#include "Device.h"
// 设备基础方法实现
Device::Device(int id, DeviceType type, const Config& config)
    : id(id), type(type), status(DeviceStatus::OFFLINE), currentConfig(config) 
{
    // 初始化时从数据库加载持久化配置
    try {
        auto& db = Database::getInstance();
        auto result = db.executeQuery(
            "SELECT config_json FROM device_settings WHERE device_id=?",
            {std::to_string(id)});
        
        if (result.hasData()) {
            // 解析JSON配置更新currentConfig
        }
    } catch (const DatabaseException& e) {
        Logger::logError("Load config failed for device " + std::to_string(id));
    }
}
void Device::control(const std::string& sessionToken,
                    const std::string& command,
                    const std::unordered_map<std::string, std::string>& params)
{
    // 权限验证
    auto& userManager = UserManager::getInstance();
    if (!userManager.checkPermission(sessionToken, 
                                    Permission::DEVICE_CONTROL, 
                                    this->id)) {
        throw DeviceException("Permission denied", id);
    }
    // 状态校验
    validateOperation();
    // 执行具体设备命令
    try {
        std::lock_guard<std::mutex> lock(configMutex);
        executeCommand(command, params);
        
        // 记录操作日志
        Logger::logSecurity("Device " + std::to_string(id) + 
                           " executed command: " + command);
    } catch (const std::exception& e) {
        updateStatus(DeviceStatus::ERROR);
        throw DeviceException("Control failed: " + std::string(e.what()), id);
    }
}
void Device::updateStatus(DeviceStatus newStatus) {
    std::lock_guard<std::mutex> lock(statusMutex);
    status.store(newStatus);
    
    // 触发回调通知
    std::vector<StatusCallback> localCallbacks;
    {
        std::lock_guard<std::mutex> cbLock(callbackMutex);
        localCallbacks = statusCallbacks;
    }
    
    for (const auto& cb : localCallbacks) {
        cb(newStatus);
    }
    // 持久化状态到数据库
    try {
        std::lock_guard<std::mutex> dbLock(dbSyncMutex);
        Database::getInstance().executePrepared(
            "UPDATE devices SET status=? WHERE id=?",
            {std::to_string(static_cast<int>(newStatus)), 
             std::to_string(id)});
    } catch (const DatabaseException& e) {
        Logger::logError("Update status failed for device " + std::to_string(id));
    }
}